import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: tgy
 * @Date: 2020-07-28 11:10
 */


class Data{

    private volatile int count;

    private Lock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();


    public void producer(){


        lock.lock();

        try {

            // 这里一定要使用while做判断
            while (count > 0 && count < 3){
                condition.await();
            }
            count++;
            System.out.println("生产者生产,总共 " + count);

            condition.signalAll();
        }catch (Exception e){

            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }


    public void customer(){

        lock.lock();

            try {

                while (count == 0){
                    condition.await();
                }

                count--;
                System.out.println("消费者消费了一个，剩余" + count);

                condition.signalAll();
            }catch (Exception e){

                e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

}


public class ProducerAndCustomerLockTest {

    public static void main(String[] args) {

        Data data = new Data();

        for (int i = 0; i < 10; i++) {

            new Thread(()->{

                data.producer();
            }).start();
        }

        for (int i = 0; i < 10;i++){

            new Thread(()->{

                data.customer();
            }).start();
        }


        while (Thread.activeCount() > 2){

            Thread.yield();
        }


    }
}
